package com.cs.code;

import com.cs.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * 解码器
 * 请求对象
 */
public class RpcDecoder extends MessageToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;
        this.serializer = serializer;
    }


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, Object o, List list) throws Exception {

        if (clazz != null && o instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf)o;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            list.add(serializer.deserialize(clazz, bytes));
        }

    }
}
